package union2;

/**
 * @Author yuh
 * @Date Created in 上午8:22 2018/4/3
 * @Description
 */
public class UnionFind {

    private int count;
    private int[] parent;
    private int[] rank;


    public UnionFind(int count) {
        this.count = count;
        parent = new int[count];
        rank = new int[count];
        for (int i = 0; i < count; i++) {
            parent[i] = i;
            rank[i] = 1;
        }
    }

    public int find(int p) {
        if (p != parent[p]) {
            p = find(parent[p]);
        }
        return p;
    }

    public boolean isConnected(int p1, int p2) {
        return find(p1) == find(p2);
    }


    public void union(int p, int q) {
        int pRoot = find(p);
        int qRoot = find(q);

        if (rank[pRoot] < rank[qRoot]) {
            parent[pRoot] = qRoot;
        } else if (rank[pRoot] > rank[qRoot]) {
            parent[qRoot] = pRoot;
        } else {
            parent[qRoot] = pRoot;
            rank[pRoot] += 1;
        }
    }

}
